<template>
  <div class="bookmark-sync-gitee">
    <div class="header">
      <h2>书签同步Gitee</h2>
    </div>
    <div class="settings-form">
      <div class="form-group">
        <label for="giteeUrl">Gitee 仓库地址</label>
        <input type="text" v-model="giteeUrl" name="giteeUrl" id="giteeUrl"
          placeholder="https://gitee.com/xxx/xxx.git" class="form-input">
      </div>
      <div class="form-group">
        <label for="access_token">访问令牌</label>
        <input type="text" v-model="accessToken" name="access_token" id="access_token"
          placeholder="123456789abcdefghigklmnopqrstuvw" class="form-input">
      </div>
      <div class="form-actions">
        <button @click="saveSettings" class="btn btn-primary">提交</button>
        <button @click="pullBookmarks" class="btn btn-secondary">拉取</button>
        <button @click="openSettings" class="btn btn-outline">设置</button>
      </div>
    </div>

    <div class="sync-controls">
      <button @click="syncBookmarks" :disabled="isSyncing" class="btn btn-success">
        {{ isSyncing ? 'Syncing...' : 'Sync Bookmarks' }}
      </button>
      <div class="sync-status">{{ syncStatus }}</div>
    </div>

    <div class="bookmark-list-container">
      <div class="bookmark-list-header">
        <h3>书签列表</h3>
      </div>
      <div class="bookmark-list">
        <div v-if="bookmarks.length === 0 && !isLoading" class="empty-state">No bookmarks found</div>
        <div v-if="isLoading" class="loading">Loading bookmarks...</div>
        <div v-for="bookmark in bookmarks" :key="bookmark.id" class="bookmark-item">
          <a :href="bookmark.url" target="_blank" class="bookmark-title">{{ bookmark.title }}</a>
          <div class="bookmark-actions">
            <button @click="syncSingleBookmark(bookmark)" class="btn btn-sm btn-primary">Sync</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import GiteeApiHelper from '../utils/giteeApiHelper.js';

export default {
  name: 'BookmarkSyncGitee',
  data() {
    return {
      bookmarks: [],
      isLoading: false,
      isSyncing: false,
      syncStatus: '',
      giteeUrl: '',
      accessToken: '',
      giteeApi: null
    }
  },
  mounted() {
    this.loadBookmarks();
    // Load saved settings if any
    this.loadSettings();
  },
  methods: {
    loadBookmarks() {
      this.isLoading = true;
      // Load bookmarks from Chrome
      if (chrome && chrome.bookmarks) {
        chrome.bookmarks.getTree((bookmarkTreeNodes) => {
          this.bookmarks = this.extractBookmarks(bookmarkTreeNodes);
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
        this.syncStatus = 'Chrome bookmarks API not available';
      }
    },
    extractBookmarks(nodes) {
      let bookmarks = [];
      const traverse = (nodes) => {
        nodes.forEach(node => {
          if (node.url) {
            bookmarks.push({
              id: node.id,
              title: node.title,
              url: node.url,
              dateAdded: node.dateAdded,
              dateGroupModified: node.dateGroupModified
            });
          }
          if (node.children) {
            traverse(node.children);
          }
        });
      };
      traverse(nodes);
      return bookmarks;
    },
    initGiteeApi() {
      if (!this.accessToken) {
        this.syncStatus = '请先输入Gitee访问令牌';
        return false;
      }
      if (!this.giteeApi) {
        this.giteeApi = new GiteeApiHelper(this.accessToken);
      } else {
        this.giteeApi.setAccessToken(this.accessToken);
      }
      return true;
    },
    parseRepoUrl() {
      // 解析仓库URL，提取所有者和仓库名
      const match = this.giteeUrl.match(/gitee\.com\/(\w+)\/(\w+)(?:\.git)?/);
      if (!match) {
        this.syncStatus = '无效的Gitee仓库URL';
        return null;
      }
      return {
        owner: match[1],
        repo: match[2]
      };
    },
    async syncBookmarks() {
      if (!this.initGiteeApi()) return;
      const repoInfo = this.parseRepoUrl();
      if (!repoInfo) return;

      this.isSyncing = true;
      this.syncStatus = '正在同步所有书签...';

      try {
        // 将书签转换为JSON字符串
        const bookmarksJson = JSON.stringify(this.bookmarks, null, 2);
        // 编码为Base64
        const base64Content = btoa(unescape(encodeURIComponent(bookmarksJson)));

        // 上传到Gitee
        await this.giteeApi.createOrUpdateFile(
          repoInfo.owner,
          repoInfo.repo,
          'bookmarks.json',
          base64Content,
          'Sync bookmarks from Chrome'
        );

        this.syncStatus = '书签同步成功！';
      } catch (error) {
        console.error('同步书签失败:', error);
        this.syncStatus = `同步失败: ${error.message}`;
      } finally {
        this.isSyncing = false;
      }
    },
    async syncSingleBookmark(bookmark) {
      if (!this.initGiteeApi()) return;
      const repoInfo = this.parseRepoUrl();
      if (!repoInfo) return;

      this.syncStatus = `正在同步书签: ${bookmark.title}...`;

      try {
        // 先获取现有书签
        let existingBookmarks = [];
        try {
          const fileInfo = await this.giteeApi.getFileContent(
            repoInfo.owner,
            repoInfo.repo,
            'bookmarks.json'
          );
          const decodedContent = decodeURIComponent(escape(atob(fileInfo.content)));
          existingBookmarks = JSON.parse(decodedContent);
        } catch (error) {
          // 如果文件不存在，将创建新文件
          if (error.message.includes('404')) {
            existingBookmarks = [];
          } else {
            throw error;
          }
        }

        // 检查是否已存在
        const index = existingBookmarks.findIndex(b => b.id === bookmark.id);
        if (index >= 0) {
          // 更新现有书签
          existingBookmarks[index] = bookmark;
        } else {
          // 添加新书签
          existingBookmarks.push(bookmark);
        }

        // 保存更新后的书签
        const bookmarksJson = JSON.stringify(existingBookmarks, null, 2);
        const base64Content = btoa(unescape(encodeURIComponent(bookmarksJson)));

        await this.giteeApi.createOrUpdateFile(
          repoInfo.owner,
          repoInfo.repo,
          'bookmarks.json',
          base64Content,
          `Sync single bookmark: ${bookmark.title}`
        );

        this.syncStatus = `书签同步成功: ${bookmark.title}`;
      } catch (error) {
        console.error('同步单个书签失败:', error);
        this.syncStatus = `同步失败: ${error.message}`;
      }
    },
    saveSettings() {
      // Save settings to Chrome storage
      if (chrome && chrome.storage) {
        chrome.storage.sync.set({
          giteeUrl: this.giteeUrl,
          accessToken: this.accessToken
        }, () => {
          this.syncStatus = '设置保存成功！';
        });
      } else {
        this.syncStatus = 'Chrome存储API不可用';
      }
    },
    loadSettings() {
      // Load settings from Chrome storage
      if (chrome && chrome.storage) {
        chrome.storage.sync.get(['giteeUrl', 'accessToken'], (result) => {
          if (result.giteeUrl) this.giteeUrl = result.giteeUrl;
          if (result.accessToken) this.accessToken = result.accessToken;
        });
      }
    },
    async pullBookmarks() {
      if (!this.initGiteeApi()) return;
      const repoInfo = this.parseRepoUrl();
      if (!repoInfo) return;

      this.syncStatus = '正在从Gitee拉取书签...';
      this.isLoading = true;

      try {
        // 从Gitee获取书签
        const fileInfo = await this.giteeApi.getFileContent(
          repoInfo.owner,
          repoInfo.repo,
          'bookmarks.json'
        );
        const decodedContent = decodeURIComponent(escape(atob(fileInfo.content)));
        const giteeBookmarks = JSON.parse(decodedContent);

        // 更新本地书签
        this.bookmarks = giteeBookmarks;
        this.syncStatus = '书签拉取成功！';
      } catch (error) {
        console.error('拉取书签失败:', error);
        this.syncStatus = `拉取失败: ${error.message}`;
      } finally {
        this.isLoading = false;
      }
    },
    openSettings() {
      // Open settings page or modal
      this.syncStatus = '打开设置...';
      // In a real implementation, you would open a settings modal or page here
    }
  }
}
</script>

<style scoped>
.bookmark-sync-gitee {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  padding: 16px;
  width: 420px;
  background-color: #f9fafb;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eaeaea;
}

.header h2 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0;
}

.settings-form {
  background-color: white;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #4a5568;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s, color 0.2s;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  background-color: #64748b;
  color: white;
}

.btn-secondary:hover {
  background-color: #475569;
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #d1d5db;
  color: #64748b;
}

.btn-outline:hover {
  background-color: #f1f5f9;
}

.btn-success {
  background-color: #42b983;
  color: white;
}

.btn-success:hover {
  background-color: #3aa876;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.sync-controls {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sync-status {
  color: #666;
  font-size: 0.9rem;
  min-height: 20px;
  margin-top: 5px;
}

.bookmark-list-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.bookmark-list-header {
  padding: 12px 16px;
  background-color: #f1f5f9;
  border-bottom: 1px solid #eaeaea;
}

.bookmark-list-header h3 {
  margin: 0;
  font-size: 1rem;
  color: #4a5568;
}

.bookmark-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px 0;
}

.bookmark-item {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.1s;
}

.bookmark-item:hover {
  background-color: #f9fafb;
}

.bookmark-title {
  color: #3b82f6;
  text-decoration: none;
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bookmark-title:hover {
  text-decoration: underline;
}

.bookmark-actions {
  display: flex;
  gap: 5px;
}

.loading {
  color: #666;
  padding: 20px 16px;
  text-align: center;
}

.empty-state {
  color: #94a3b8;
  padding: 40px 16px;
  text-align: center;
  font-style: italic;
}
</style>